<template>
	<el-dialog v-model="dialogVisible" :title="`${typeName + classifyName}分类`" width="40%" center @close="dialogClose">
		<el-form :model="classifyForm" label-position="right" label-width="150px" ref="ruleFormRef" :rules="rules" style="30%">
			<el-form-item :label="`${classifyName}分类名称`" prop="name">
				<el-input v-model="classifyForm.name" />
			</el-form-item>

			<el-form-item label="排序" prop="sort">
				<el-input v-model.number="classifyForm.sort" />
			</el-form-item>
		</el-form>

		<template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogClose">取消</el-button>
				<el-button type="primary" @click="submit(ruleFormRef)"> 提交 </el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="ClassifyDialog">
	import { defineProps, defineEmits, toRefs, reactive, ref, onMounted } from 'vue'
	import type { FormInstance, FormRules } from 'element-plus'
	import { ElMessage } from 'element-plus'
	import { saveClassify, updateClassify } from '@/api/index'
	import { ItableData } from '../classifyManage.vue'

	type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>
	type IclassifyForm = Optional<ItableData, 'createTime' | 'createUser' | 'id' | 'updateTime' | 'updateUser'>

	// 接收父组件传参
	const props = defineProps<{
		dialogVisible: boolean
		classifyName: string
		typeName: string
		editRow: IclassifyForm | null
	}>()

	// 定义 state 数据类型
	interface Istate {
		classifyForm: IclassifyForm
	}

	// 定义 state 响应式数据
	const state: Istate = reactive({
		classifyForm: {
			name: '',
			sort: null,
			type: -1
		}
	})

	// 定义表单校验
	const ruleFormRef = ref<FormInstance>()
	const rules = reactive<FormRules>({
		name: [{ required: true, message: '必填', trigger: 'blur' }],
		sort: [{ required: true, message: '必填', trigger: 'blur' }]
	})

	// 使用 toRefs 将数据解构出去
	const { dialogVisible, classifyName } = toRefs(props)
	const { classifyForm } = toRefs(state)

	const emit = defineEmits(['dialogClose', 'getTableData'])

	onMounted(() => {
		if (props.editRow) {
			state.classifyForm = props.editRow
		}
	})

	/**
	 * 新增分类
	 */
	const submit = async (formEl: FormInstance | undefined) => {
		if (!formEl) return
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				try {
					let res
					state.classifyForm.type = props.classifyName === '菜品' ? 1 : 2
					if (state.classifyForm.id) {
						res = await updateClassify<string>(state.classifyForm)
					} else {
						res = await saveClassify<string>(state.classifyForm)
					}

					emit('dialogClose')
					emit('getTableData')
					ElMessage.success(res?.data)
				} catch (error) {
					ElMessage({
						type: 'error',
						message: error as string
					})
				}
			} else {
				console.log('error submit!', fields)
			}
		})
	}

	const dialogClose = () => {
		emit('dialogClose')
	}
</script>

<style scoped lang="scss"></style>
